package com.nintendo.service.impl;

import com.nintendo.service.ChatRecordService;
import com.nintendo.service.OllamaService;
import com.nintendo.utils.ChatTypeEnum;
import com.nintendo.utils.SSEMsgType;
import com.nintendo.utils.SSEServer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OllamaServiceImpl implements OllamaService {
    @Resource
    private OllamaChatClient ollamaChatClient;
    @Resource
    private ChatRecordService chatRecordService;
    @Override
    public Object aiOllamaChat(String msg) {
        return ollamaChatClient.call(msg);
    }

    @Override
    public Flux<ChatResponse> stream(Prompt prompt) {
        return ollamaChatClient.stream(prompt);
    }

    @Override
    public List<String> stream2(String msg) {
        Prompt prompt = new Prompt(new UserMessage(msg));
        Flux<ChatResponse> streamResponse = ollamaChatClient.stream(prompt);
        List<String> list = streamResponse.toStream().map(chatResponse -> {
            String content = chatResponse.getResult().getOutput().getContent();
            log.info("{}",content);
            return content;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public void doDoctorV3(String username, String message) {
        // 保存用户发送的记录到数据库
        chatRecordService.saveChatRecord(username,message, ChatTypeEnum.USER);
        Prompt prompt = new Prompt(new UserMessage(message));
        Flux<ChatResponse> streamResponse = ollamaChatClient.stream(prompt);
        List<String> list = streamResponse.toStream().map(chatResponse -> {
            String content = chatResponse.getResult().getOutput().getContent();
            SSEServer.sendMessage(username,content, SSEMsgType.ADD);
            return content;
        }).collect(Collectors.toList());
        SSEServer.sendMessage(username,"[FINISH]", SSEMsgType.FINISH);
        String htmlResult = "";
        for (String s : list) {
            htmlResult+=s;
        }
        chatRecordService.saveChatRecord(username,htmlResult, ChatTypeEnum.BOT);
    }


}
